import java.util.ArrayList;
import java.util.List;

class Solution {

    int m = 0;
    int n = 0;
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};



    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        m = heights.length;
        n = heights[0].length;

        boolean[][] pacific = new boolean[m][n];
        boolean[][] atlantic = new boolean[m][n];

        for(int i = 0; i < m; i++){
            dfs(heights, i, 0, pacific);
            dfs(heights, i, n - 1, atlantic);
        }
        for(int j = 0; j < n; j++){
            dfs(heights, 0, j, pacific);
            dfs(heights, m - 1, j, atlantic);
        }
        List<List<Integer>> ret  = new ArrayList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                List<Integer> point = new ArrayList<>();
                if(pacific[i][j] == true && atlantic[i][j] == true){
                    point.add(i);
                    point.add(j);
                    ret.add(point);
                }
            }
        }
        return ret;
    }

    public void dfs(int[][] heights, int i, int j, boolean[][] check){
        check[i][j] = true;
        for(int k = 0; k < 4; k++){
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && heights[x][y] >= heights[i][j] && check[x][y] == false){
                dfs(heights, x, y, check);
            }
        }
    }
}